//
//  UPNetworkPermissionChecker.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/19.
//

#import "UPNetworkPermissionChecker.h"
#import <UIKit/UIKit.h>

@implementation UPNetworkPermissionChecker

+ (void)checkCellularPermissionWithCompletion:(void (^)(UPNetworkPermissionStatus))completion {
    CTCellularData *cellularData = [[CTCellularData alloc] init];
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UPNetworkPermissionStatus status;
            switch (state) {
                case kCTCellularDataRestricted:
                    status = UPNetworkPermissionStatusRestricted;
                    break;
                case kCTCellularDataNotRestricted:
                    status = UPNetworkPermissionStatusNotRestricted;
                    break;
                case kCTCellularDataRestrictedStateUnknown:
                default:
                    status = UPNetworkPermissionStatusUnknown;
                    break;
            }
            if (completion) completion(status);
        });
    };
}

+ (BOOL)isNetworkReachable {
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com");
    SCNetworkReachabilityFlags flags;
    BOOL success = SCNetworkReachabilityGetFlags(reachability, &flags);
    CFRelease(reachability);
    
    if (success) {
        BOOL isReachable = (flags & kSCNetworkReachabilityFlagsReachable);
        BOOL needsConnection = (flags & kSCNetworkReachabilityFlagsConnectionRequired);
        return isReachable && !needsConnection;
    }
    return NO;
}

@end
